package com.wahoyu.exportwordtest.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wahoyu.exportwordtest.api.RemoteVisualService;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * OpenFeign请求类
 * @Author wanghongyu02
 * @Date 2025/4/22 16:05
 */
@Slf4j
@Service
public class HttpRequestService {

//    @Value("${reqUrl}")
    private String requestUrl = "";

    @Autowired
    private RemoteVisualService remoteVisualService;

    public List<JSONObject> getDataByFeign(Map<String, String> reqMap, String functionName) {

        if (reqMap == null || reqMap.isEmpty()) {
            throw new RuntimeException("接口请求参数为空！");
        }

        // 过滤null值参数
        Map<String, String> filteredMap = reqMap.entrySet().stream()
                .filter(entry -> entry.getValue() != null)
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        // 构建日志参数
        String params = filteredMap.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
        log.info("[Feign接口请求] {}?{}", "/visual/report/data", params);

        try {
            JSONObject response = remoteVisualService.getVisualReportData(new HashMap<>(filteredMap));
            log.info("[Feign接口返回] {}", response);

            JSONObject data = response.getJSONObject("data");
            if (data == null) {
                throw new RuntimeException(functionName + "返回data为空，[错误信息] " + response.getString("msg"));
            }

            JSONArray rows = data.getJSONArray("rows");
            return JSON.parseArray(rows.toString(), JSONObject.class);

        } catch (FeignException e) {
            log.error("Feign请求失败，状态码：{}，原因：{}", e.status(), e.getMessage());
            throw new RuntimeException(functionName + "请求接口失败，响应码：" + e.status());
        } catch (Exception e) {
            log.error("接口请求异常：{}", e.getMessage());
            throw new RuntimeException(functionName + "请求接口异常：" + e.getMessage());
        }
    }

    public List<JSONObject> getData(Map<String, String> reqMap, String functionName) {

        if (reqMap == null || reqMap.isEmpty()) {
            throw new RuntimeException("接口请求参数为空！");
        }

        String params = reqMap.entrySet().stream()
                .filter(entry -> entry.getValue() != null)  // 过滤掉值为 null 的 entry
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
        String reqUrl = requestUrl + "?" + params;
        log.info("[接口请求] {}", reqUrl);

        try {
            // 创建URL对象并建立连接
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            // 检查响应状态码
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应内容
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();

                // 使用Fastjson解析JSON
                JSONObject root = JSON.parseObject(response.toString());
                log.info("[接口返回] {}", root);
                JSONObject data = root.getJSONObject("data");
                if (data == null) {
                    throw new RuntimeException(functionName + "返回data为空，[错误信息] " + root.getString("msg"));
                }
                JSONArray rows = data.getJSONArray("rows");

                return JSON.parseArray(rows.toString(), JSONObject.class);
            } else {
                throw new RuntimeException(functionName + "请求接口失败，响应码：" + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new ArrayList<>();
    }
}